package App.Service;

import App.Model.Account.CrmUser;
import App.Model.Friend.*;
import App.Model.JPush.JPushCustomerContent;
import App.Model.Xinge.XinGeCustomerContent;
import App.Repository.FriendRepository;
import App.Repository.TaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * Created by xw on 2019/1/14.
 */

@Service
public class FriendService {

    @Autowired
    private FriendRepository _repository;

    @Autowired
    private XingeService _xinge;

    @Autowired
    private JPushService _jPushService;

    public int insertFriend(FriendSaveRequest _request, int userid) throws Exception {

        return _repository.insertFriend(_request, userid);
    }


    public int deleteFriend(FriendDeleteRequest _request, int userid) throws Exception {
        return _repository.deleteFriend(_request, userid);
    }


    public List<FriendListResponse> getFriendList(FriendListRequest _request, int userid) {
        return _repository.getFriendList(_request, userid);

    }

    public List<FriendListResponse> getFriendSearchList(FriendListRequest _request, int userid) {
        return _repository.getFriendSearchList(_request, userid);

    }

    public List<FriendContactListResponse> getContactList(FriendListRequest _request, int userid) {
        return _repository.getContactList(_request, userid);

    }

    public FriendMeResponse getUserInfo(int userid, int myUserId) {
        return _repository.getUserInfo(userid, myUserId);
    }

    public FriendMeResponse getUserInfo(int userid) {
        return _repository.getUserInfo(userid);
    }

    public int updateUserMeInfo(FriendMeSaveRequest _request, int userid) throws Exception {
        return _repository.updateUserMeInfo(_request, userid);

    }

public List<FriendListResponse> getContactApplyList(int userid) {
    List<FriendListResponse> contactApplyList = _repository.getContactApplyList(userid);
    return contactApplyList.stream().filter(distinctByKey1(FriendListResponse::getPhone)).collect(Collectors.toList());
}

/**
 * <p>安字段去重</p >
 *
 * @param keyExtractor
 * @param <T>
 * @return
 * @author Wangjian
 */
static <T> Predicate<T> distinctByKey1(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}

    public int inertContactApply(FriendContractApplySaveRequest _request, int userid) throws Exception {

        int _result = _repository.inertContactApply(_request, userid);
        if (_result > 0) {

            FriendMeResponse _me = _repository.getUserInfo(userid);
            String _userName = _me.getRealname();

            List<String> _userids = new ArrayList<>();
            for (Integer id : _request.getUserids()) {
                _userids.add(Integer.toString(id));
            }
            String _title = "添加好友申请";
            String _messageTemplate = "%s申请加为好友";
            String _message = String.format(_messageTemplate, _userName);

            //极光推送
            Collection<String> alias = new LinkedList<String>();
            List<CrmUser> _users = _repository.getUserInfoList(_userids);
            for (CrmUser u : _users) {
                alias.add(u.getUsername());
            }

            JPushCustomerContent cc = new JPushCustomerContent();
            cc.setKey("e1117369b0a39e42185042aa");
            cc.setProjectid("3a95002c4cfe848816fc18db");
            cc.setPushType("addFriend");
            _jPushService.sendPushByAliasCustomer(alias, _title, _message, cc);

            //信鸽推送
//            XinGeCustomerContent _customerContent = new XinGeCustomerContent();
//            _customerContent.setPushType("addFriend");
//            _xinge.pushCustomerMessageAndroid("", "", _userids, _title, _message, _customerContent);
//            _xinge.pushCustomerMessageIos("", "", _userids, _title, _message, _customerContent);
        }
        return _result;
    }

    public int updateContactApplyStatus(FriendApplyPassRequest request, int applyStatus) throws Exception {
        int _result = _repository.updateContactApplyStatus(request, applyStatus);
        if (_result > 0) {

            String _taskid = "";
            List<String> _userids = new ArrayList<>();
            List<CrmContractApply> _applys = _repository.getContactApply(request.getRecid());
            if (_applys != null && _applys.size() > 0) {
                int _fromUserId = _applys.get(0).getFromuserid();
                int _toUserId = _applys.get(0).getTouserid();
                _userids.add(Integer.toString(_fromUserId));

                FriendMeResponse _user = _repository.getUserInfo(_toUserId);
                String _userName = _user.getRealname();

                String _messageTemplate = "%s已经通过了您的好友申请";
                String _message = String.format(_messageTemplate, _userName);


                String _title = "好友申请通过";
                Collection<String> alias = new LinkedList<String>();
                List<CrmUser> _users = _repository.getUserInfoList(_userids);
                for (CrmUser u : _users) {
                    alias.add(u.getUsername());
                }
                JPushCustomerContent cc = new JPushCustomerContent();
                cc.setKey("e1117369b0a39e42185042aa");
                cc.setProjectid("3a95002c4cfe848816fc18db");
                cc.setPushType("addFriendConfirm");
                _jPushService.sendPushByAliasCustomer(alias, _title, _message, cc);


                //_xinge.pushMessage(_taskid, "", _userids, "好友申请通过", _message);

//                XinGeCustomerContent _customerContent = new XinGeCustomerContent();
//                _customerContent.setPushType("addFriendConfirm");
//                _xinge.pushCustomerMessageAndroid("", "", _userids, _title, _message, _customerContent);
//                _xinge.pushCustomerMessageIos("", "", _userids, _title, _message, _customerContent);
            }
        }

        return _result;

    }


    public int getUnReadFriendApply(int userid) {
        return _repository.getUnReadFriendApply(userid);
    }

    @Transactional
    public void setApplyHasViewed(int userid) {
        _repository.setApplyHasViewed(userid);

    }

    public int addExpertiseFile(CrmUserExpertiseItemRequest _request, int userid) {
        int _result = _repository.addExpertiseFile(_request, userid);
        return _result;
    }

    public int deleteExpertiseFile(CrmUserExpertiseItemDeleteRequest _request, int userid) {
        int _result = 0;
        for (String recid : _request.getRecids()) {
            _result = _repository.deleteExpertiseFile(recid, userid);
        }
        return _result;
    }

    public List<CrmUserExpertiseResponse> getExpertisesList(int userId) {
        return _repository.getExpertisesList(userId);
    }
}
